import os

from fastapi import UploadFile
from minio import Minio

from exceptions.exception import ServiceException


def _init_minio():
    minio_client = Minio(
        os.getenv("MINIO_SERVER"),
        os.getenv("MINIO_ACCESS_KEY"),
        os.getenv("MINIO_SECRET_KEY"),
        secure=True,
    )
    return minio_client

# 检查存储桶是否存在，不存在则创建
def check_bucket(minio_client: Minio, bucket_name: str):
    try:
        print(minio_client.bucket_exists(bucket_name))
        if not minio_client.bucket_exists(bucket_name):
            minio_client.make_bucket(bucket_name)
    except Exception as e:
        raise ServiceException(message='minio 创建桶异常')

def upload_file_to_minio(file: UploadFile):
    minio_client = _init_minio()
    try:
        bucket_name = os.getenv("MINIO_BUCKET")
        # 检查存储桶是否存在
        check_bucket(minio_client, bucket_name)
        result = minio_client.put_object(
            bucket_name,
            file.filename,
            file.file,
            content_type = get_content_type(file.filename),
            length=file.size,
        )
        # 生成下载 URL
        download_url = "https://" + os.getenv("MINIO_SERVER")+"/"+os.getenv("MINIO_BUCKET")+"/"+file.filename
        return {"message": True, "download_url": download_url, "file_name": file.filename}
    except Exception as e:
        raise ServiceException(message=False)

def download_file_from_minio(file_name: str):
    #初始化minio客户端
    minio_client = _init_minio()
    print(file_name)
    bucket_name = os.getenv("MINIO_BUCKET")
    try:
        bucket_name = os.getenv("MINIO_BUCKET")
        check_bucket(minio_client, bucket_name)
        return minio_client.get_object(bucket_name, file_name)
    except Exception as e:
        return e


def get_file_type(file_name):
    # 获取文件扩展名
    _, extension = os.path.splitext(file_name)
    extension = extension.lower()  # 转换为小写

    # 定义图片和视频的扩展名
    image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
    video_extensions = {".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv"}

    if extension in image_extensions:
        return "image"
    elif extension in video_extensions:
        return "video"
    else:
        return "unknown"

def get_content_type(filename):
    file_type = get_file_type(filename)
    if file_type == 'video':
        return 'video/mp4'
    return 'application/octet-stream'
